package com.annhoa.domain.service;
import com.annhoa.domain.entity.SysUser;
import com.annhoa.domain.repository.SysUserRepository;
import com.annhoa.infrastructure.security.JwtAuthenticationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.annhoa.domain.repository.SysUserJpaRepository;
import com.annhoa.infrastructure.common.PageData;
import com.annhoa.infrastructure.security.JwtTokenUtil;
import java.util.Date;

@Service
public class AuthServiceImpl implements AuthService {

    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;
    private JwtTokenUtil jwtTokenUtil;
    private SysUserRepository sysUserRepository;
    private SysUserJpaRepository sysUserJpaRepository;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    public AuthServiceImpl(
            AuthenticationManager authenticationManager,
            @Qualifier("customUserService")
            UserDetailsService userDetailsService,
            JwtTokenUtil jwtTokenUtil,
            SysUserRepository sysUserRepository) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.sysUserRepository = sysUserRepository;
    }

    @Override
    public SysUser register(SysUser sysUserToAdd) {
        String username = sysUserToAdd.getUsername();
        if(sysUserRepository.findByUsername(username)!=null) {
            return null;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = sysUserToAdd.getPassword();
        sysUserToAdd.setPassword(encoder.encode(rawPassword));
        sysUserToAdd.setLastPasswordResetDate(new Date());
//        userToAdd.setRoles(asList("ROLE_USER"));
        return sysUserJpaRepository.save(sysUserToAdd);
    }

    @Override
    public JwtAuthenticationResponse login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        Authentication authentication = authenticationManager.authenticate(upToken);
        // TODO 可通过写入redis 替换 context
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        String token = jwtTokenUtil.generateToken(userDetails);
        return new JwtAuthenticationResponse(tokenHead + token);
    }
    @Override
    public Object loginPage(PageData pd) {
    	String username = pd.getString("username");
    	String password = pd.getString("password");
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        String token = jwtTokenUtil.generateToken(userDetails);
        pd.put("token", tokenHead+token);
        pd.put("object", userDetails);
        return pd;
    }
    @Override
    public JwtAuthenticationResponse refresh(String oldToken) {
        String token = oldToken.substring(tokenHead.length());
        String username = jwtTokenUtil.getUsernameFromToken(token);
        SysUser sysUser = (SysUser) userDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.canTokenBeRefreshed(token, sysUser.getLastPasswordResetDate())){
            return new JwtAuthenticationResponse(tokenHead + jwtTokenUtil.refreshToken(token));
        }
        return null;
    }
}